<?php 
namespace Admin\Controller;
use \Think\Controller;

class LoginController extends Controller{


	// 执行登录操作
	public function dologin()
	{
		$user = I('post.adminname');
		$password = I('post.password');
		// 查管理员用户表
		$usertable = M('adminuser');

		$where['adname'] = $user;
		$userInfo = $usertable->where($where)->find();
		if ($userInfo['status'] == '0') {
			$this->error('您的账户处于禁用状态,请联系管理员...','',5);
		}else{
			if (!empty($userInfo) & $userInfo['adpassword'] == md5($password)) {
				$_SESSION['adname'] = $user;
				$_SESSION['aduid'] = $userInfo['aduid'];
				$_SESSION['logtime'] = $userInfo['logtime'];
				$_SESSION['lognum'] = $userInfo['lognum'];
				$_SESSION['ip'] = $userInfo['ip'];
				// 将登录时间戳存入数据库
				$id = $userInfo['aduid'];
				$data['logtime'] = time();
				$data['ip'] = get_client_ip();
				$data['lognum'] = $userInfo['lognum'] + 1;
				$map['aduid'] = $id;
				$result = $usertable->where($map)->save($data);

			} else {
				$this->error('用户名或密码错误!');
				$this->redirect('User/login');
				exit;
			}
		}
		


		$userid = $userInfo['aduid'];
		// var_dump($userInfo) ;

		// 查询用户角色表
		$user_role_table = M('user_role');

		$where["aduid"] = $userid;
		$user_role_data = $user_role_table->where($where)->select();

		// var_dump($user_role_data);

		// 遍历出角色ID,另存为一个数组
		$roleid = array();
		foreach ($user_role_data as $key => $value) {
			foreach ($value as $k => $v) {
				if ($k == 'roleid') {
					$roleid[] = $v;
				}
			}
		}

		// var_dump($roleid);

		// 查询角色-权限表
		$role_node_table = M('role_node');
		$map['roleid'] = array('in',$roleid);
		$role_node_data = $role_node_table->where($map)->select();
		// echo $role_node_table->getLastSql();

		// var_dump($role_node_data);
		// 遍历所有节点ID
		$nodeid = array();
		foreach ($role_node_data as $key => $value) {
			foreach ($value as $k => $v) {
				if ($k == 'nodeid') {
					$nodeid[] = $v;
				}
			}
		}
		// var_dump($nodeid);

		// 查询权限表 
		$node_table = M('node');
		$condition['nodeid'] = array('in',$nodeid);
		$node_data = $node_table->where($condition)->select();

		// var_dump($node_data);die;

		// 遍历出控制器和方法  并存入session中
		foreach ($node_data as $key => $value) {
			$_SESSION['node'][] = $value['controller'].'_'.$value['method'];
		}
		$this->redirect('Index/index');
	}

	// 退出登录
	public function loginOut()
	{
		unset($_SESSION['aduid']);
		unset($_SESSION['adminname']);
		unset($_SESSION['node']);
		unset($_SESSION['logtime']);
		unset($_SESSION['lognum']);
		unset($_SESSION['ip']);
		$this->redirect('Admin/login');
	}
}